package dao

import (
	"context"
	"fmt"
	"github.com/aphasia51/website/internal/domain"
	"gorm.io/gorm"
)

type ChemicalDAO struct {
	db *gorm.DB
}

func NewChemicalDap(db *gorm.DB) *ChemicalDAO {
	return &ChemicalDAO{
		db: db,
	}
}

func (dao *ChemicalDAO) Query(ctx context.Context, c domain.Chemical) ([]Chemical, error) {
	var chemicals []Chemical
	db := dao.db

	if chemical := c.Chemical; chemical != "" {
		chemical = fmt.Sprintf("%%%v%%", chemical)
		db = db.WithContext(ctx).Where("name like ?", chemical)
	}
	// todo: fix code
	//if similarChemical := c.SimilarChemical; similarChemical != "" {
	//	similarChemical = fmt.Sprintf("%%%v%%", similarChemical)
	//	db = db.WithContext(ctx).Where("similarChemical like ?", similarChemical)
	//}
	// todo: find if in hazardous_chemical table
	//if ifHazardousChemical := c.IfHazardousChemical; ifHazardousChemical != "" {
	//	ifHazardousChemical = fmt.Sprintf("%%%v%%", ifHazardousChemical)
	//	db = db.WithContext(ctx).Where("ifHazardousChemical like ?", ifHazardousChemical)
	//}
	//if c.Chemical == "" && c.SimilarChemical == "" && c.IfHazardousChemical == "" {
	//	return []Chemical{}, nil
	//}
	err := db.Debug().WithContext(ctx).Find(&chemicals).Error
	if err != nil {
		fmt.Println("query error")
	}
	return chemicals, nil
}

func (dao *ChemicalDAO) Select(ctx context.Context) ([]Chemical, error) {
	var chemicals []Chemical
	db := dao.db

	err := db.Debug().WithContext(ctx).Select("id", "name", "dict_name").Find(&chemicals).Error
	if err != nil {
		fmt.Println("query error")
	}
	return chemicals, nil
}

type Chemical struct {
	Id       string `gorm:"autoIncrement,primary_key"`
	Name     string `gorm:"name"`
	DictName string `gorm:"dict_name"`
	Stock    string `gorm:"stock"`
	//Date            string
	//Specification   string
	//ActualQuantity  string
	//StorageLocation string
	//DateManufacture string
	//CAS             string
	//LaboratoryRoom  string
}
